package com.wolfeyes.common.typehandler;

import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.symmetric.AES;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;

import java.nio.charset.StandardCharsets;
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * @see Talk is cheap, Show me the code. -- Linus Torvalds
 * @title 处理加解密的TypeHandler处理器
 * @author yanyljava
 * @create 2021-05-18 09:20
 */
@MappedJdbcTypes(JdbcType.VARCHAR)
@MappedTypes(Encrypt.class)
public class EncryptTypeHandler extends BaseTypeHandler<Encrypt> {

	private static final byte[] KEYS = "12345678abcdefgh".getBytes(StandardCharsets.UTF_8);

	/**
	 * @title 设置参数
	 */
	@Override
	public void setNonNullParameter(PreparedStatement ps, int i, Encrypt parameter, JdbcType jdbcType) throws SQLException {
		if (parameter == null || parameter.getValue() == null) {
			ps.setString(i, null);
			return ;
		}
		AES aes = SecureUtil.aes(KEYS);
		String encrypt = aes.encryptHex(parameter.getValue());
		ps.setString(i, encrypt);
	}

	/**
	 * @title 获取值
	 */
	@Override
	public Encrypt getNullableResult(ResultSet rs, String columnName) throws SQLException {
		
		return decrypt(rs.getString(columnName));
	}

	/**
	 * @title 获取值
	 */
	@Override
	public Encrypt getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
		
		return decrypt(rs.getString(columnIndex));
	}

	/**
	 * @title 获取值
	 */
	@Override
	public Encrypt getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
		
		return decrypt(cs.getString(columnIndex));
	}

	public Encrypt decrypt(String value) {
		if (null == value) {
			return null;
		}
		
		return new Encrypt(SecureUtil.aes(KEYS).decryptStr(value));
	}
	
}


